package com.cy.module;

import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Menu;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.List;

@ControllerBind(controllerKey = "/clmp/menu")
public class MenuController extends WebApiController {

    @Override
    public void index(){
        Long pid = getParaToLong("id");
        Integer type = getParaToInt("type");
        List<Menu> menuList = Menu.dao.findByParent(pid, type);
        for (Menu menu : menuList){
            menu.put("leaf", menu.getChildren().size() == 0);
        }
        renderJson(JsonKit.toJson(menuList, 20));
    }

    @Override
    public void show(){
    }

    @Override
    @Before(Tx.class)
    public void update(){
        int id = getParaToInt();
        Menu tempMenu = getModel(Menu.class);
        Menu menu = Menu.dao.findById(id);
        //是否改了资源类型
        boolean isUpdatedType = !tempMenu.getType().equals(menu.getType());
        menu.coverExclude(tempMenu, null);

        try{
            menu.update();
            //级联更新子菜单类型
            if (isUpdatedType){
                menu.updateTypeCascade();
            }
            renderSuccess();
        } catch (Exception e){
            e.printStackTrace();
            renderFail();
        }
    }

    @Override
    public void save(){
        Menu menu = getModel(Menu.class);
        if (menu.save()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    @Before(Tx.class)
    public void delete(){
        try{
            Menu menu = Menu.dao.findById(getParaToInt());
            menu.deleteCascade();
            renderSuccess();
        } catch (Exception e){
            renderFail("请先删除子菜单！");
        }
    }

    /**
     * 获取所有父选项
     */
    public void getParentItems(){
        Integer type = getParaToInt("type");
        renderJson(Menu.dao.findAllByType(type));
    }
}